<template>
  <div class="avatar-uploader">
    <el-upload
      ref="uploadRef"
      class="avatar-uploader-container"
      :auto-upload="false"
      :show-file-list="false"
      :on-change="handleFileChange"
      :disabled="uploading"
      accept="image/jpeg,image/jpg,image/png,image/gif,image/webp"
    >
      <div class="avatar-wrapper" :class="{ uploading: uploading }">
        <el-image
          v-if="avatarUrl && !uploading"
          :src="avatarUrl"
          class="avatar-image"
          fit="cover"
          :preview-src-list="[avatarUrl]"
          :initial-index="0"
          preview-teleported
        >
          <template #error>
            <div class="avatar-placeholder">
              <el-icon><Picture /></el-icon>
              <span>头像</span>
            </div>
          </template>
        </el-image>

        <div v-else-if="uploading" class="avatar-uploading">
          <el-icon class="uploading-icon"><Loading /></el-icon>
          <span>上传中...</span>
        </div>

        <div v-else class="avatar-placeholder">
          <el-icon><Plus /></el-icon>
          <span>上传头像</span>
        </div>

        <!-- 悬浮操作按钮 -->
        <div v-if="avatarUrl && !uploading" class="avatar-actions">
          <el-button
            type="primary"
            size="small"
            :icon="Upload"
            circle
            title="更换头像"
            @click.stop="triggerUpload"
          />
          <el-button
            type="danger"
            size="small"
            :icon="Delete"
            circle
            title="删除头像"
            @click.stop="handleDeleteAvatar"
          />
        </div>
      </div>
    </el-upload>

    <!-- 上传提示 -->
    <div class="upload-tips">
      <p>支持 JPG、PNG、GIF、WebP 格式</p>
      <p>文件大小不超过 5MB</p>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted, watch } from "vue";
import { ElMessage, ElMessageBox, type UploadInstance } from "element-plus";
import {
  Plus,
  Upload,
  Delete,
  Picture,
  Loading
} from "@element-plus/icons-vue";

import {
  uploadAvatarApi,
  deleteFileApi,
  FileUploadType,
  UnifiedFileUploadUtils,
  type UnifiedFileUploadResult
} from "@/api/unified-upload";
import {
  deleteMyAvatarApi,
  getMyAvatarApi,
  deleteUserAvatarApi
} from "@/api/upload";

interface Props {
  // 用户ID，如果提供则为管理员模式，可以上传其他用户的头像
  userId?: number;
  // 初始头像URL
  initialAvatar?: string;
  // 是否禁用
  disabled?: boolean;
  // 头像尺寸
  size?: number;
}

interface Emits {
  (e: "success", result: UnifiedFileUploadResult): void;
  (e: "delete"): void;
  (e: "error", error: any): void;
}

const props = withDefaults(defineProps<Props>(), {
  disabled: false,
  size: 120
});

const emit = defineEmits<Emits>();

// 响应式数据
const uploadRef = ref<UploadInstance>();
const avatarUrl = ref<string>("");
const uploading = ref(false);

// 计算属性
const isAdminMode = computed(() => !!props.userId);

/**
 * 格式化头像URL
 */
const formatAvatarUrl = (url: string): string => {
  if (!url) return "";

  // 如果已经是完整URL，直接返回
  if (url.startsWith("http://") || url.startsWith("https://")) {
    return url;
  }

  // 如果是相对路径，添加基础URL
  const baseURL = import.meta.env.DEV
    ? "http://localhost:8081"
    : "http://localhost:8081";
  return baseURL + url;
};

// 监听初始头像变化
watch(
  () => props.initialAvatar,
  newVal => {
    console.log("初始头像变化:", newVal);
    if (newVal) {
      const formattedUrl = formatAvatarUrl(newVal);
      console.log("格式化后的头像URL:", formattedUrl);
      avatarUrl.value = formattedUrl;
    } else {
      avatarUrl.value = "";
    }
  },
  { immediate: true }
);

// 组件挂载时获取头像
onMounted(async () => {
  if (!isAdminMode.value && !props.initialAvatar) {
    await loadMyAvatar();
  }
});

/**
 * 加载当前用户头像
 */
const loadMyAvatar = async () => {
  try {
    console.log("开始加载当前用户头像...");
    const result = await getMyAvatarApi();
    console.log("获取头像API响应:", result);
    if (result.code === 200 && result.data) {
      const formattedUrl = formatAvatarUrl(result.data);
      console.log("设置头像URL:", formattedUrl);
      avatarUrl.value = formattedUrl;
    } else {
      console.log("没有头像数据或响应失败");
    }
  } catch (error) {
    console.error("获取头像失败:", error);
  }
};

/**
 * 文件选择处理
 */
const handleFileChange = async (file: any) => {
  console.log("文件选择:", file);

  if (!file || !file.raw) {
    console.error("无效的文件对象");
    ElMessage.error("无效的文件对象");
    return;
  }

  try {
    uploading.value = true;
    console.log("开始文件验证...");

    // 使用统一工具类进行验证
    const validation = UnifiedFileUploadUtils.validateFile(
      file.raw,
      FileUploadType.AVATAR
    );
    console.log("文件验证结果:", validation);

    if (!validation.valid) {
      ElMessage.error(validation.message || "文件验证失败");
      uploading.value = false;
      return;
    }

    console.log("开始上传文件...");
    // 手动上传文件
    await uploadFile(file.raw);
  } catch (error) {
    console.error("文件处理失败:", error);
    ElMessage.error(error.message || "文件处理失败");
    uploading.value = false;
  }
};

/**
 * 上传文件
 */
const uploadFile = async (file: File) => {
  try {
    console.log("上传文件详情:", {
      name: file.name,
      size: file.size,
      type: file.type,
      isAdminMode: isAdminMode.value,
      userId: props.userId
    });

    // 使用统一头像上传接口
    console.log("使用统一头像上传接口");
    const result = await uploadAvatarApi(file);

    console.log("上传API响应:", result);

    if (result.code === 200) {
      avatarUrl.value = formatAvatarUrl(result.data.fileUrl);
      ElMessage.success(result.message || "头像上传成功");
      emit("success", result.data);
    } else {
      console.error("上传失败，响应码:", result.code, "消息:", result.message);
      ElMessage.error(result.message || "上传失败");
      emit("error", result);
    }
  } catch (error) {
    console.error("上传异常:", error);
    ElMessage.error("上传失败，请重试");
    emit("error", error);
  } finally {
    uploading.value = false;
  }
};

/**
 * 触发文件选择
 */
const triggerUpload = () => {
  uploadRef.value?.clearFiles();
  const input = uploadRef.value?.$el.querySelector('input[type="file"]');
  input?.click();
};

/**
 * 删除头像
 */
const handleDeleteAvatar = async () => {
  try {
    await ElMessageBox.confirm("确定要删除头像吗？", "确认删除", {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      type: "warning"
    });

    // 调用删除API
    const result = isAdminMode.value
      ? await deleteUserAvatarApi(props.userId!)
      : await deleteMyAvatarApi();

    if (result.code === 200) {
      avatarUrl.value = "";
      ElMessage.success(result.message || "头像删除成功");
      emit("delete");
    } else {
      ElMessage.error(result.message || "删除失败");
    }
  } catch (error) {
    if (error !== "cancel") {
      console.error("删除头像失败:", error);
      ElMessage.error("删除失败，请重试");
    }
  }
};

// 暴露方法给父组件
defineExpose({
  triggerUpload,
  loadMyAvatar
});
</script>

<style lang="scss" scoped>
.avatar-uploader {
  display: flex;
  flex-direction: column;
  gap: 12px;
  align-items: center;
}

.avatar-uploader-container {
  :deep(.el-upload) {
    position: relative;
    overflow: hidden;
    cursor: pointer;
    border: 2px dashed var(--el-border-color);
    border-radius: 8px;
    transition: all 0.3s;

    &:hover {
      border-color: var(--el-color-primary);
    }
  }
}

.avatar-wrapper {
  position: relative;
  display: flex;
  align-items: center;
  justify-content: center;
  width: v-bind("`${props.size}px`");
  height: v-bind("`${props.size}px`");

  &.uploading {
    pointer-events: none;
  }
}

.avatar-image {
  width: 100%;
  height: 100%;
  border-radius: 6px;
}

.avatar-placeholder,
.avatar-uploading {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  font-size: 14px;
  color: var(--el-text-color-secondary);

  .el-icon {
    margin-bottom: 8px;
    font-size: 28px;
  }
}

.avatar-uploading {
  .uploading-icon {
    animation: rotate 2s linear infinite;
  }
}

.avatar-actions {
  position: absolute;
  top: 50%;
  left: 50%;
  display: flex;
  gap: 8px;
  opacity: 0;
  transform: translate(-50%, -50%);
  transition: opacity 0.3s;

  .avatar-wrapper:hover & {
    opacity: 1;
  }

  .el-button {
    background-color: rgb(255 255 255 / 80%);
    backdrop-filter: blur(4px);
  }
}

.upload-tips {
  font-size: 12px;
  line-height: 1.4;
  color: var(--el-text-color-secondary);
  text-align: center;

  p {
    margin: 0;
  }
}

@keyframes rotate {
  from {
    transform: rotate(0deg);
  }

  to {
    transform: rotate(360deg);
  }
}
</style>
